const formidable = require("formidable");
const path = require("path");
const fs = require("fs");
/*
* req:请求对象
* picName:图片的名字
* ok:  1,请选择上传的内容。2、上传格式不正确，3成功
* */
module.exports.upPic = function (req,picName) {
    const form = new formidable.IncomingForm();
    form.uploadDir = path.resolve(__dirname,"../upload");
    form.keepExtensions=true;
    return new Promise((resolve,reject)=>{
        form.parse(req,function (err,params,file) {
            const picInfo = file[picName];
            console.log(picName,picInfo);
            if(picInfo){
                if(picInfo.size < 1){
                    fs.unlink(picInfo.path,function () {
                        resolve({
                            ok:1,
                            msg:"请选择上传的内容"
                        })
                    })

                }else{
                    const extname = path.extname(picInfo.path).toLowerCase();
                    const extArr = [".png",".gif",".jpg",".bmp"];
                    if(extArr.includes(extname)){
                        params[picName] = Date.now()+extname;
                        fs.rename(picInfo.path,path.resolve(__dirname,"../upload/"+params[picName]),function () {
                            resolve({
                                ok:3,
                                params,
                                msg:"上传成功"
                            })
                        })
                    }else{
                        fs.unlink(picInfo.path,function () {
                            resolve({
                                ok:2,
                                msg:"请提交符合要求的图片：.png,.gif,.jpg,.bmp"
                            })
                        })

                    }
                }
            }
            else{
                resolve({
                    ok:1,
                    params,
                    msg:"请选择上传的内容"
                })
            }

        })
    })

}